//
//  LLEmoticonViewController.swift
//  表情键盘
//
//  Created by Bingo on 15/11/5.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit

class LLEmoticonViewController: UIViewController {
    
    
    // MARK: - 属性
    private var collectionViewCellIdentifier = "collectionViewCellIdentifier"
    
    weak var textView:UITextView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        prepareUI()
    }
    private func prepareUI(){
        
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["cv":collectionView , "tb":toolBar]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        setupToolBar()
        setupCollectionView()
        
    }
    
    
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        
        var index = 0
        for package in  packages{
            
            let button = UIButton()
            
            let name = package.group_name_cn
            
            button.setTitle(name, forState: UIControlState.Normal)
            
            // 设置颜色
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            
            button.sizeToFit()
            
            button.tag = index + baseTag
            
            if index == 0{
                
                switchSelectedButton(button)
                
            }
            
            button.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            let item = UIBarButtonItem(customView: button)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        
        items.removeLast()
        
        toolBar.items = items
    }
    func itemClick(button:UIButton){
        
        let indexPath = NSIndexPath(forItem: 0, inSection: button.tag - baseTag)
        
        print("滚动到section = \(indexPath.section)")
        collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.Left)
        
        
        switchSelectedButton(button)
    }
    
    private func switchSelectedButton(buttton:UIButton){
        selectedButton?.selected = false
        
        buttton.selected = true
        
        selectedButton = buttton
        
    }
    private var selectedButton:UIButton?
    
    private let baseTag = 1000
    
    private func setupCollectionView(){
        
        collectionView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        collectionView.dataSource = self
        
        collectionView.delegate = self
        
        collectionView.registerClass(LLEmoticonCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
        
    }
    
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LLCollectionViewFlowLayout())
    
    private lazy var toolBar = UIToolbar()
    
    
    private lazy var packages = LLEmoticonPackage.packages
}

extension LLEmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! LLEmoticonCell
        
        let emoticon = packages[indexPath.section].emoticons?[indexPath.item]
        
        cell.emoticon = emoticon
        
        return cell
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        if let indexPath = collectionView.indexPathsForVisibleItems().first{
            
            let section = indexPath.section
            
            print("停止滚动section:\(section)")
            
            let button = toolBar.viewWithTag(section + baseTag) as!UIButton
            
            print("查找到的按钮的tag:\(button.tag)")
            
            switchSelectedButton(button)
        }
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("点击了")
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        textView?.insertEmoticon(emoticon)
        
        if indexPath.section != 0 {
            
            LLEmoticonPackage.addFavorate(emoticon)
       }
    }
}

class LLEmoticonCell:UICollectionViewCell{
    
    var emoticon:LLEmoticon?{
        
        didSet{
//            print("emoticon.png:\(emoticon?.pngPath)")
            
            if let pngPath = emoticon?.pngPath{
                
                emoticonButton.setImage(UIImage(contentsOfFile: pngPath), forState: UIControlState.Normal)
                
            }else{
                emoticonButton.setImage(nil, forState: UIControlState.Normal)
            }
            
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.removeEmoticon{
                
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame:CGRect){
        
        super.init(frame:frame)
        
        prepareUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI(){
        contentView.addSubview(emoticonButton)
        
        
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        
        emoticonButton.userInteractionEnabled = false
        
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
    }
    
    
    private lazy var emoticonButton : UIButton = UIButton()
    
}

class LLCollectionViewFlowLayout: UICollectionViewFlowLayout{
    
    override func prepareLayout() {
        super.prepareLayout()
        
        let width = collectionView!.frame.width / 7.0
        
        let height = collectionView!.frame.height / 3.0
        
        itemSize = CGSize(width: width, height: height)
        
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        minimumLineSpacing = 0
        
        minimumInteritemSpacing = 0
        
        collectionView?.bounces = false
        collectionView?.alwaysBounceHorizontal = false
        
        collectionView?.showsHorizontalScrollIndicator = false
        
        collectionView?.pagingEnabled = true
    }
}